package com.msi.manning.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Result extends Activity {
    private static final String CLASSTAG = Result.class.getSimpleName();

	public static final int MAIN_ID = Menu.FIRST;
    
    private TextView factof;
    private EditText gram;
    // CHANGED
/*
    private TextView calories;
    private TextView total_fat;
    private TextView sugar_tot;
    private TextView sodium;
    private TextView cholestrl;
    private TextView vitamin_c;
    private TextView protein;
    private TextView calcium;
*/
    
    private String choice;
    private ListView nutrients;
    ArrayList<HashMap<String, String>> facts;
    
    @Override
    public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        Log.d(Constants.LOGTAG, "Entered Result.java");
        
        // Getting Data first.
        Bundle extras = getIntent().getExtras();
        if (extras != null)
        {
        	choice = extras.getString("choices");
        	Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " Choice = " + choice);
        }
        else
        {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + "No Choice passed");
        }
        	
        final String url = "http://teamsupercool.x10hosting.com/result2.php?keyword=" + choice;
        // Stores into facts
        this.facts = getHttpResponse(url);
        
        // Start Window.
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.result);
    	Log.d(Constants.LOGTAG, "Main Layout Set");

        this.factof 	= (TextView) findViewById(R.id.factof);
        this.gram		= (EditText) findViewById(R.id.amount);
        this.gram.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
		    	Log.d(Constants.LOGTAG, "User Inputted: " + s.toString());
		        ArrayList<HashMap<String, String>> tfacts = new ArrayList<HashMap<String, String>>();
		        HashMap<String, String> tmap = new HashMap<String, String>();
		        if (!s.toString().equals(""))
		    	{
		    		DecimalFormat df = new DecimalFormat("0.###");
		    		for (HashMap<String,String> eNut : facts) {
		    			String newValue = df.format(
		    					Double.valueOf(eNut.get("value")).doubleValue() 
		    					/ 100 * Integer.parseInt(s.toString())
		    			);
		    			tmap.put("cat", eNut.get("cat"));
		    			tmap.put("value", newValue);
		    			tfacts.add(tmap);
		    			tmap = new HashMap<String, String>();
		    		}
		    		initListView(tfacts);
		    	}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}
        });
        /* Leaving just in case.
        this.calories 	= (TextView) findViewById(R.id.calories_val);
        this.total_fat 	= (TextView) findViewById(R.id.total_fat_val);
        this.sugar_tot 	= (TextView) findViewById(R.id.sugar_tot_val);
        this.sodium 	= (TextView) findViewById(R.id.sodium_val);
        this.cholestrl 	= (TextView) findViewById(R.id.cholestrl_val);
        this.vitamin_c 	= (TextView) findViewById(R.id.vitamin_c_val);
        this.protein 	= (TextView) findViewById(R.id.protein_val);
        this.calcium 	= (TextView) findViewById(R.id.calcium_val);
         */
        this.nutrients = (ListView) findViewById(R.id.list_of_nutrients);
    	Log.d(Constants.LOGTAG, "View Binded");

    	// Set choice
        factof.setText(choice);
        initListView();
        /*
        if(facts.containsKey("Energ_Kcal"))
        	calories.setText(facts.get("Energ_Kcal") + " kcal");
        if(facts.containsKey("Tot_Fat"))
        	total_fat.setText(facts.get("Tot_Fat") + " g");
        if(facts.containsKey("Sugar_Tot"))
        	sugar_tot.setText(facts.get("Sugar_Tot") + " g");
        if(facts.containsKey("Sodium"))
        	sodium.setText(facts.get("Sodium") + " mg");
        if(facts.containsKey("Cholestrl"))
        	cholestrl.setText(facts.get("Cholestrl") + " mg");
        if(facts.containsKey("Vit_C"))
        	vitamin_c.setText(facts.get("Vit_C") + " mg");
        if(facts.containsKey("Protein"))
        	protein.setText(facts.get("Protein") + " g");
        if(facts.containsKey("Calcium"))
        	calcium.setText(facts.get("Calcium") + " mg");
        	*/
    }
    
        
    private void initListView() {
        /* Loads the items to the ListView. 
         * 
         * SimpleAdapter ( , list<Hash, /layout/nutriant.xml, mapping..)
         * 
         */
    	nutrients.setAdapter(new SimpleAdapter(this, facts, R.layout.nutriant,
    			new String[] {"cat", "value"}, 
    			new int[] {R.id.CAT_CELL, R.id.VALUE_CELL}));
    }
    
    
    private void initListView(ArrayList<HashMap<String, String>> tfacts) {
        /* Loads the items to the ListView. 
         * 
         * SimpleAdapter ( , list<Hash, /layout/nutriant.xml, mapping..)
         * 
         */
    	nutrients.setAdapter(new SimpleAdapter(this, tfacts, R.layout.nutriant,
    			new String[] {"cat", "value"}, 
    			new int[] {R.id.CAT_CELL, R.id.VALUE_CELL}));
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, MAIN_ID, 0, R.string.menu_main);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
        case MAIN_ID:
            startActivity(new Intent(Result.this, NutritionMe.class));
            return true;
        }
       
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * Perform an HTTP GET with HttpUrlConnection.
     * 
     * @param location
     * @return
     */
    private ArrayList<HashMap<String, String>> getHttpResponse(String location) {
        URL url = null;
        //HashMap<String, String> items = new HashMap<String, String>();
        ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
        Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " location = " + location);

        try {
            url = new URL(location);
            Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " url = " + url);
        } catch (MalformedURLException e) {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " " + e.getMessage());
        }

        if (url != null) {

           // this.progressDialog = ProgressDialog.show(this, "working . . .", "performing HTTP request");
        	
        	try 
        	{
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()), 16384);
                
                /*
                char a;
                while ((a = (char) in.read()) != -1)
                	inputLine += a;*/
                String x;
                HashMap<String, String> nutrient = new HashMap<String, String>();
                while (!(x = in.readLine()).startsWith("EOF"))
                {
                	String[] tresult = x.split("::");
                	Log.d(Constants.LOGTAG, x + " " + tresult[0] + " : " + tresult[1]);
                	if(!tresult[1].equals("0.000"))
                	{
                		nutrient.put("cat", tresult[0]);
                		nutrient.put("value", tresult[1]);
                		items.add(nutrient);
                		nutrient = new HashMap<String, String>();
                	}
                }
                
                /*
                if (!inputLine.startsWith("Shrt_Desc"))
                	throw new IOException("Nutritional Value is currently unavailable");
                
                // split
                String[] result = new String[24];
                String[] inputs0 = inputLine.split("Shrt_Desc:");
                result[0] = "Shrt_Desc";
                String temp = inputs0[1];
                String[] inputs1 = temp.split("Energ_Kcal:");
                result[1] = inputs1[0];
                result[2] = "Energ_Kcal";
                temp = inputs1[1];
                String[] inputs2 = temp.split("Tot_Fat:");
                result[3] = inputs2[0];
                result[4] = "Tot_Fat";
                temp = inputs2[1];
                String[] inputs3 = temp.split("FA_Sat:");
                result[5] = inputs3[0];
                result[6] = "FA_Sat";
                temp = inputs3[1];
                String[] inputs4 = temp.split("Cholestrl:");
                result[7] = inputs4[0];
                result[8] = "Cholestrl";
                temp = inputs4[1];
                String[] inputs5 = temp.split("Sodium:");
                result[9] = inputs5[0];
                result[10] = "Sodium";
                temp = inputs5[1];
                String[] inputs6 = temp.split("Carbohydrt:");
                result[11] = inputs6[0];
                result[12] = "Carbohydrt";
                temp = inputs6[1];
                String[] inputs7 = temp.split("Sugar_Tot:");
                result[13] = inputs7[0];
                result[14] = "Sugar_Tot";
                temp = inputs7[1];
                String[] inputs8 = temp.split("Fiber_TD:");
                result[15] = inputs8[0];
                result[16] = "Fiber_TD";
                temp = inputs8[1];
                String[] inputs9 = temp.split("Protein:");
                result[17] = inputs9[0];
                result[18] = "Protein";
                temp = inputs9[1];
                String[] inputs10 = temp.split("Vit_C:");
                result[19] = inputs10[0];
                result[20] = "Vit_C";
                temp = inputs10[1];
                String[] inputs11 = temp.split("Calcium:");
                result[21] = inputs11[0];
                result[22] = "Calcium";
                result[23] = inputs11[1];
                
                for (int i = 0; i < result.length; i+=2)
                {
                	Log.v(Constants.LOGTAG, " " + Result.CLASSTAG + " inputLine = " + result[i] + result[i + 1]);
                	items.put(result[i],result[i+1]);
                }
				*/

                in.close();
                urlConn.disconnect();

            } catch (IOException e) {
                Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " " + e.getMessage());
            }

            //this.progressDialog.dismiss();
        } else {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " url NULL");
        }
        return items;
    }
    
}
